package com.dong8.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dong8.R;
import com.dong8.resp.FourDaysResp;
import com.dong8.resp.SpaceInfo;
import com.dong8.resp.SpaceInfo.Section;
import com.dong8.resp.SpaceInfo.Space;
import com.dong8.sys.MyApp;
import com.dong8.util.DateUtil;
import com.dong8.util.MgqDataHandler;
import com.dong8.util.MgqRestClient;
import com.dong8.util.TLog;
import com.dong8.util.ToastUtil;
import com.loopj.android.http.RequestParams;

@SuppressLint("SimpleDateFormat")
@SuppressWarnings("unused")
public class OrderFieldActivity extends Activity implements View.OnClickListener 
{
	private ViewPager viewPager; // android-support-v4中的滑动组件
	private List<View> imageViews = new ArrayList<View>();

	Button m_select_button;
	
	public List<Section > mShowList = new ArrayList<Section >();
	public List<Section > mSectionList = null;
	public List<Space > mSpaceList;
	public List<String> mOrderInfo;
	
	public List<String> mPeriodId = new ArrayList<String>();
	public List<String> mFieldId = new ArrayList<String>();

	public List<String> mMyOrderInfo = new ArrayList<String>();
	OrderAdapter m_adapter;
	
	FieldAdapter mFieldAdapter;
	int mSelectedDate = 0;
	public List<Integer> mSelectedArray = new ArrayList<Integer>();
	
	OnClickListener mFieldListener = new OnClickListener()
	{
		@Override
		public void onClick(View arg0) 
		{
			List<String> tag = (List<String>)arg0.getTag();
			for(String index : tag)
			{
				if(mMyOrderInfo.contains(index))
				{
					mMyOrderInfo.remove(index);
					((Button)arg0).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.icon2_room);
				}
				else
				{
					mMyOrderInfo.add(index);
					((Button)arg0).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.icon4_room);
				}
			}
			
			if(tag.size() == 0)
			{
				ToastUtil.showToastWithAlertPic("您还没有选择运动时间");
			}
			
			int total = 10*mMyOrderInfo.size();
			((TextView)findViewById(R.id.total)).setText("￥" +total);
			m_adapter.notifyDataSetChanged();
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_field);

		initUI();

		((MyApp)getApplicationContext()).mFinishActivity = this;
	}
	
	private void initUI()
	{
		String mtypeId = getIntent().getStringExtra("mtypeId");
		if (mtypeId.equals("badminton")) 
		{
			((TextView) findViewById(R.id.tv_title)).setText("羽毛球");
		} 
		else if (mtypeId.equals("tableTennis")) 
		{
			((TextView) findViewById(R.id.tv_title)).setText("乒乓球");
		} 
		else if (mtypeId.equals("bowling")) 
		{
			((TextView) findViewById(R.id.tv_title)).setText("保龄球");
		}
		
		findViewById(R.id.ibBack).setOnClickListener(this);
		findViewById(R.id.apply).setOnClickListener(this);

		Calendar c = Calendar.getInstance();
		long second = System.currentTimeMillis();
		for (int i = 0; i < 3; i++) {//  显示3屏 
			LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View convertView = mInflater.inflate(R.layout.item_time, null);
			imageViews.add(convertView);

			for (int j = 0; j < 4; j++) {// 每屏幕显示4个 
				Date date = new Date(second);
				String dateStr = new SimpleDateFormat("MM月dd日").format(date);

				try 
				{
					c.setTime(date);
					dateStr += "\n" + DateUtil.week(c.get(Calendar.DAY_OF_WEEK));
				}
				catch (ParseException e) 
				{
					e.printStackTrace();
				}

				Button tv = (Button) convertView.findViewById(R.id.order_time_0 + j);
				tv.setId(R.id.order_time_0 + 4*i + j);
				tv.setOnClickListener(this);
				tv.setText(dateStr);
				second += 24 * 3600 * 1000;//  时间 +1 天  

				if (i == 0 && j == 0) 
				{// 第一天选中  
					m_select_button = (Button) tv;
					m_select_button.setSelected(true);
					m_select_button.setTextColor(Color.rgb(113, 124, 156));
				}
			}
		}

		viewPager = (ViewPager) findViewById(R.id.vp);
		viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器
		viewPager.setOnPageChangeListener(new MyPageChangeListener());
		//-------------
		getSpaceData();
		
		ListView listview = (ListView)findViewById(R.id.listView);
		m_adapter = new OrderAdapter();
		listview.setAdapter(m_adapter);
	}
	
	private class MyPageChangeListener implements OnPageChangeListener 
	{
		public void onPageSelected(int position) {}
		public void onPageScrollStateChanged(int arg0) {}
		public void onPageScrolled(int arg0, float arg1, int arg2) {}
	}

	class OrderAdapter extends BaseAdapter 
	{
		public int getCount() {
			return mMyOrderInfo.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			ViewHolder holder = null;
			if (convertView == null) 
			{
				holder = new ViewHolder();

				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = mInflater.inflate(R.layout.item_field_reserve, null);
				holder.title = (TextView) convertView.findViewById(R.id.title);
				holder.time = (TextView) convertView.findViewById(R.id.time);
				convertView.setTag(holder);
			}
			else 
			{
				holder = (ViewHolder) convertView.getTag();
			}

			String orderInfo = mMyOrderInfo.get(position);
			int pos = orderInfo.indexOf("-");
			String order = orderInfo.substring(0, pos);
			
			Section section = mSectionList.get(mPeriodId.indexOf(order));
			orderInfo = orderInfo.substring(pos + 1);
			pos = orderInfo.indexOf("-");
			orderInfo = orderInfo.substring(pos + 1);
			pos = orderInfo.indexOf("-");
			orderInfo = orderInfo.substring(pos + 1);
			
			String name = "场地" + orderInfo;
			String time = section.period;
			
			holder.title.setText(name);
			holder.time.setText(time);
			return convertView;
		}
	}

	public final class ViewHolder 
	{
		public TextView title;
		public TextView time;
	}
	
	class FieldAdapter extends BaseAdapter 
	{
		public int getCount() {
			return mShowList.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			FieldHolder holder = null;
			if (convertView == null) 
			{
				holder = new FieldHolder();

				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = mInflater.inflate(R.layout.item_order_field, null);
				holder.time = (TextView) convertView.findViewById(R.id.time);
				convertView.setTag(holder);
			}
			else
			{
				holder = (FieldHolder) convertView.getTag();
			}

			Section section = mShowList.get(position);
			holder.time.setText(section.period);
			
			if(mSelectedArray.contains(position))
			{
				convertView.setBackgroundColor(Color.rgb(234, 99, 51));
				holder.time.setTextColor(Color.WHITE);
			}
			else
			{
				convertView.setBackgroundColor(Color.WHITE);
				holder.time.setTextColor(Color.rgb(64, 64, 64));
			}
			
			return convertView;
		}
	}

	public final class FieldHolder 
	{
		public TextView time;
	}
	
	private class MyAdapter extends PagerAdapter {
		@Override
		public int getCount() {
			return imageViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(imageViews.get(arg1));
			return imageViews.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}

	/**
	 * 获取场地的信息,  有多少个场地，时间段   
	 */
	private void getSpaceData()
	{
		String url = getIntent().getStringExtra("service") + "/club/getSpaceInfo"; 
		MgqDataHandler handler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				super.onSuccess(response);
				TLog.i("hansen", "=======response=="+response);
				
				SpaceInfo spaceInfo = JSON.parseObject(response, SpaceInfo.class);
				if (spaceInfo.code == 0) 
				{
					TLog.i("hansen", "=======::period:"+spaceInfo.sectionList.get(2).period);
					
					mSectionList = spaceInfo.sectionList;
					mSpaceList = spaceInfo.spaceList;
					mShowList.addAll(mSectionList);
					
					mFieldAdapter = new FieldAdapter();
					ListView mListView1 = (ListView) findViewById(R.id.listView1);
					mListView1.setAdapter(mFieldAdapter);
					mListView1.setOnItemClickListener(new OnItemClickListener()
					{
						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) 
						{
							if(mSelectedArray.contains(Integer.valueOf(arg2))) mSelectedArray.remove(Integer.valueOf(arg2));
							else mSelectedArray.add(Integer.valueOf(arg2));

							mMyOrderInfo.removeAll(mMyOrderInfo);
							m_adapter.notifyDataSetChanged();
							((TextView)findViewById(R.id.total)).setText("￥0");
							
							mFieldAdapter.notifyDataSetChanged();
							setFieldState();
						}
					});
					mListView1.setSelection(0);
					
					LinearLayout layout = (LinearLayout)findViewById(R.id.field_layout);
					LayoutInflater inflater = LayoutInflater.from(OrderFieldActivity.this);

					int count = mSpaceList.size();
					int len = count/3;
					if(count%3 > 0) len++;
					Section section = mShowList.get(0);
					int sid = section.sid;
					for(int i = 0; i < len; i++)
					{
						View convertView = inflater.inflate(R.layout.item_field_layout, null);
						
						Space space = mSpaceList.get(i*3);
						Button button = (Button)convertView.findViewById(R.id.field_0);
						button.setText("场地" + space.item_name);
						button.setId(20000 + 3*i);
						button.setOnClickListener(mFieldListener);
						button.setTag(new ArrayList<String>().add(sid + "-" + space.item_code + "-" + section.period.substring(0, 5) + "-" + space.item_name));
						mFieldId.add(space.item_code);						
						
						if(3*i + 1 < count)
						{
							space = mSpaceList.get(i*3 + 1);
							button = (Button)convertView.findViewById(R.id.field_1);
							button.setVisibility(View.VISIBLE);
							button.setText("场地" + space.item_name);
							button.setId(20000 + 3*i + 1);
							button.setOnClickListener(mFieldListener);
							button.setTag(new ArrayList<String>().add(sid + "-" + space.item_code + "-" + section.period.substring(0, 5) + "-" + space.item_name));
							mFieldId.add(space.item_code);		
						}
						
						if(3*i + 2 < count)
						{
							space = mSpaceList.get(i*3 + 2);
							button = (Button)convertView.findViewById(R.id.field_2);
							button.setVisibility(View.VISIBLE);
							button.setText("场地" + space.item_name);
							button.setId(20000 + 3*i + 2);
							button.setOnClickListener(mFieldListener);
							button.setTag(new ArrayList<String>().add(sid + "-" + space.item_code + "-" + section.period.substring(0, 5) + "-" + space.item_name));
							mFieldId.add(space.item_code);
						}
						
						layout.addView(convertView);
					}

					count = mShowList.size();
					for(int i = 0; i < count; i++)
					{
						mPeriodId.add(String.valueOf(mShowList.get(i).sid));
					}
					
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
					Date date = new Date();  
					getScheduleOfDay(sdf.format(date));
				} 
				else 
				{
					
				}
			}

			public void onFailure(Throwable ble) {
			}
		};

		RequestParams params = new RequestParams();
		params.put("movetype", getIntent().getStringExtra("fmtype_code"));
		params.put("fclut_code", getIntent().getStringExtra("fclub_code")); 	
		
		MgqRestClient.get(url, params, handler);
	}
	
	/**
	 * 获取某一天的场地信息， 要做一个 一下子可以取4天 数据的接口 
	 * @param startDate
	 * @param endDate
	 */
	private void getScheduleOfDay(String startDate){
		Date date = new Date(System.currentTimeMillis());
		String today = new SimpleDateFormat("yyyy-MM-dd").format(date); 
		
		String url = getIntent().getStringExtra("service") + "/club/getClubState"; 
		MgqDataHandler handler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response)
			{
				super.onSuccess(response);
				TLog.i("hansen", "=======response=="+response);
				
				mSelectedArray.removeAll(mSelectedArray);
				mSelectedArray.add(0);

				mFieldAdapter.notifyDataSetChanged();
				ListView mListView1 = (ListView) findViewById(R.id.listView1);
				mListView1.setSelection(0);
				((ScrollView)findViewById(R.id.scrollview)).scrollTo(0, 0);
				
				FourDaysResp resp = JSON.parseObject(response, FourDaysResp.class);
				mOrderInfo = resp.d1;
				
				mMyOrderInfo.removeAll(mMyOrderInfo);
				setFieldState();
			}

			public void onFailure(Throwable ble) 
			{
				
			}
		};

		RequestParams params = new RequestParams();
		params.put("movetype", getIntent().getStringExtra("fmtype_code"));
		params.put("fclut_code", getIntent().getStringExtra("fclub_code")); 	
		params.put("startDate", startDate); 	
		
		MgqRestClient.get(url, params, handler);
	}
	
	void setFieldState()
	{
		mShowList.removeAll(mShowList);
		
		if(mSelectedDate == 0)
		{
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
			String date = sdf.format(new Date());
			
			int count = mSectionList.size();
			int i = 0;
			for(; i < count; i++)
			{
				int result = date.compareTo(mSectionList.get(i).period);
				if(result <= 0)
				{
					break;
				}
			}
			
			mShowList.addAll(mSectionList.subList(i, count));
		}
		else
		{
			mShowList.addAll(mSectionList);
		}
		
		int count = mSpaceList.size();
		for(int i = 0; i < count; i++)
		{
			Space space = mSpaceList.get(i);
			Button button = (Button)findViewById(20000 + i);
			button.setOnClickListener(mFieldListener);
			
			ArrayList<String> array = new ArrayList<String>();
			for(Integer index : mSelectedArray)
			{
				Section section = mShowList.get(index);
				String tag = section.sid + "-" + space.item_code + "-" + section.period.substring(0, 5) + "-" + space.item_name;
				array.add(tag);
				
				if(mMyOrderInfo.contains(tag))
				{
					button.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.icon4_room);
				}
				else
				{
					button.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.icon2_room);
				}
			}
			
			button.setTag(array);
		}
		
		count = mOrderInfo.size();
		for(int i = 0; i < count; i++)
		{
			String order = mOrderInfo.get(i);
			int pos = order.indexOf("-");
			
			String sid = order.substring(0, pos);
			String time = order.substring(pos + 1);
			
			int index = mPeriodId.indexOf(sid);
			for(Integer idx : mSelectedArray)
			{
				if(index == idx + mSectionList.size() - mShowList.size())
				{
					index = mFieldId.indexOf(time);
					Button button = (Button)findViewById(20000 + index);
					button.setOnClickListener(null);
					button.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.icon1_room);
				}
			}
		}
	}

	@Override
	public void onClick(View arg0) 
	{
		if (arg0.getId() >= R.id.order_time_0 && arg0.getId() <= R.id.order_time_0 + 1000)
		{
			mSelectedDate = arg0.getId() - R.id.order_time_0;
			
			mMyOrderInfo.removeAll(mMyOrderInfo);
			m_adapter.notifyDataSetChanged();
			((TextView)findViewById(R.id.total)).setText("￥0");
			
			m_select_button.setSelected(false);
			m_select_button.setTextColor(Color.rgb(212, 219, 225));
			m_select_button = (Button) arg0;
			m_select_button.setSelected(true);
			m_select_button.setTextColor(Color.rgb(113, 124, 156));
			
			String date = ((Button)arg0).getText().toString();
			int pos = date.indexOf("\n");
			
			StringBuffer buffer = new StringBuffer();
			buffer.append("2014-");
			buffer.append(date.substring(0, pos));
			buffer.deleteCharAt(buffer.length() - 1);
			date = buffer.toString();
			date = date.replace("月", "-");

			getScheduleOfDay(date);
			return;
		}

		switch (arg0.getId())
		{
		case R.id.ibBack:
			finish();
			break;

		case R.id.apply:
		{
			if(mMyOrderInfo.size() == 0)
			{
				ToastUtil.showToastWithOkPic("您还没有选择要预定的场地");
				return;
			}
			
			String date = m_select_button.getText().toString();
			int pos = date.indexOf("\n");
			
			StringBuffer buffer = new StringBuffer();
			buffer.append("2014-");
			buffer.append(date.substring(0, pos));
			buffer.deleteCharAt(buffer.length() - 1);
			date = buffer.toString();
			date = date.replace("月", "-");
			
			StringBuffer orderItem = new StringBuffer();
			orderItem.append("['" + date + "',");
			orderItem.append("'" + getIntent().getExtras().getString("clubId") + "',");
			orderItem.append("'" + getIntent().getExtras().getString("fmtype_code") + "',");
			int count = mMyOrderInfo.size();
			for(int i = 0; i < count; i++)
			{
				if(i < count - 1) orderItem.append("'" + mMyOrderInfo.get(i) + "',");
				else  orderItem.append("'" + mMyOrderInfo.get(i) + "']");
			}
		
			JSONObject orderForm = new JSONObject();
			try 
			{
				orderForm.put("amount", 10*mMyOrderInfo.size());
				orderForm.put("club_id", getIntent().getExtras().getString("clubId"));
				orderForm.put("club_name", getIntent().getExtras().getString("club_name"));
				orderForm.put("order_desc", ((TextView) findViewById(R.id.tv_title)).getText());
				orderForm.put("id", 0);
				orderForm.put("create_time", "");
				orderForm.put("cust_name", "");
				orderForm.put("order_code", "");
				orderForm.put("order_item", orderItem.toString());
				orderForm.put("phone", "");
				orderForm.put("status", "");
				orderForm.put("user_id", "");
				orderForm.put("user_name", "");
			}
			catch (JSONException e) 
			{
				e.printStackTrace();
			}

			Intent intent = new Intent(this, ConfirmOrderActivity.class);
			intent.putExtra("orderForm", orderForm.toString());
			startActivity(intent);
		}
			break;
		}
	}
}
